<?php

namespace App\Http\Controllers\Api;

use App\Models\AdminModel;
use App\Services\LoginService;
use Validator;
use Illuminate\Http\Request;
use App\Services\UsersService;
use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\Log;

class UsersController extends BaseController
{
    /**
     * @审批人列表
     * created 在 2021/10/18 11:03 创建
     * @author SunWu
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function approverList()
    {
        return $this->success(
            UsersService::approverList($this->getMainUserId())
        );
    }

    /**
     * @子账号列表
     * created 在 2021/10/18 11:03 创建
     * @author SunWu
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function userList(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'pageSize' =>'required|integer',//页面大小
            'currentPage' =>'required|integer',//当前页
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        return $this->success(
            UsersService::userList($this->getMainUserId(), $data)
        );
    }

    /**
     * @子账号列表
     * created 在 2021/11/13 09:25 创建
     * @author SunWu
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function transStatus(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
                'id' => 'required|integer',//用户id
                'status' => [
                     'required',
                     'integer',
                     Rule::In([0,1]),
                 ],//状态;1:启用;0:禁用;
            ],
            [
                'id.required' => '参数`用户id`缺失',
                'id.integer' => '参数`用户id`只能为整型',
                'status.required' => '参数`status`缺失',
                'status.integer' => '参数`status`只能为数字',
            ]
        );

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        return response()->json(UsersService::transStatus($this->getMainUserId(), $data));
    }

    /**
     * @重置子账号密码
     * created 在 2021/10/13 10:03 创建
     * @author SunWu
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function resetPwd(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
                'id' => 'required|integer',//用户id
            ],
            [
                'id.required' => '参数`用户id`缺失',
                'id.integer' => '参数`用户id`只能为整型',
            ]
        );

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }


        return response()->json(UsersService::resetPwd($this->getMainUserId(), $data));
    }

    /**
     * @重置子账号密码
     * created 在 2021/10/13 10:18 创建
     * @author SunWu
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function delUser(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
                'id' => 'required|integer',//用户id
            ],
            [
                'id.required' => '参数`用户id`缺失',
                'id.integer' => '参数`用户id`只能为整型',
            ]
        );

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        return response()->json(UsersService::delUser($this->getMainUserId(), $data));
    }

    /**
     * @重置子账号密码
     * created 在 2021/10/13 10:25 创建
     * @author SunWu
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function addUser(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
                'username' => 'required',//用户id
                'nickname' => 'required',//用户id
                // 'mobile' => 'regex:/^1[345789][0-9]{9}$/',
                'status' => [
                     'required',
                     'integer',
                     Rule::In([0,1]),
                 ],//状态;1:启用;0:禁用;
            ],
            [
                'username.required' => '参数`账号`缺失',
                'nickname.required' => '参数`子账号昵称`缺失',
                // 'mobile.regex' => '手机号格式错误，请重试',
                'status.required' => '参数`status`缺失',
                'status.integer' => '参数`status`只能为数字',
            ]
        );

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        $accountNum = AdminModel::where('parent_id', $this->getMainUserId())
            ->where('delete_flag', 0)->count();

        if(!$this->isVip() && $accountNum >= $this->subAccountNumber()) {
            return $this->fail('', '您当前为非VIP用户，最多可创建'.$this->subAccountNumber().'个子账号');
        }

        if(!empty($data['mobile'])) {
            $checkMobile = Validator::make($data, [
                    'mobile' => 'regex:/^1[345789][0-9]{9}$/',
                ],
                [
                    'mobile.regex' => '手机号格式错误，请重试',
                ]
            );

            if ($infos = $checkMobile->errors()->first()) {
                return response()->json([
                    'code' => 1,
                    'msg' => $infos,
                    'data' => '',
                ]);
            }
        }

        return response()->json(UsersService::addUser($this->getMainUserId(), $data));
    }

    /**
     * @修改子账号信息
     * created 在 2021/10/13 15:58 创建
     * @author SunWu
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function editUserInfo(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
                'id' => 'required|integer',//用户id
                'username' => 'required',//用户id
                'nickname' => 'required',//用户id
                'status' => [
                     'required',
                     'integer',
                     Rule::In([0,1]),
                 ],//状态;1:启用;0:禁用;
            ],
            [
                'id.required' => '参数`用户id`缺失',
                'id.integer' => '参数`用户id`只能为整型',
                'username.required' => '参数`账号`缺失',
                'nickname.required' => '参数`子账号昵称`缺失',
                'status.required' => '参数`status`缺失',
                'status.integer' => '参数`status`只能为数字',
            ]
        );

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        if(!empty($data['mobile'])) {
            $checkMobile = Validator::make($data, [
                    'mobile' => 'regex:/^1[345789][0-9]{9}$/',
                ],
                [
                    'mobile.regex' => '手机号格式错误，请重试',
                ]
            );

            if ($infos = $checkMobile->errors()->first()) {
                return response()->json([
                    'code' => 1,
                    'msg' => $infos,
                    'data' => '',
                ]);
            }
        }

        return response()->json(UsersService::editUserInfo($this->getMainUserId(), $data));
    }

    /**
     * @设置子账号权限信息
     * created 在 2021/10/13 15:58 创建
     * @author SunWu
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function setUser(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
                'id' => 'required|integer',//用户id
                 'first_module' => 'required',
                 'second_module' => 'required',
            ],
            [
                'id.required' => '参数`用户id`缺失',
                'id.integer' => '参数`用户id`只能为整型',
                'first_module.required' => '参数`一级权限菜单模块`缺失',
                'second_module.required' => '参数`二级权限菜单模块`缺失',
            ]
        );

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        return response()->json(UsersService::setUser($this->getMainUserId(), $data));
    }

    /**
     * @获取子账号权限信息
     * created 在 2021/11/13 16:58 创建
     * @author SunWu
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUserPermission(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
                'id' => 'required|integer',//用户id
            ],
            [
                'id.required' => '参数`用户id`缺失',
                'id.integer' => '参数`用户id`只能为整型',
            ]
        );

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        return response()->json(UsersService::getUserPermission($this->getMainUserId(), $data));
    }

    /**
     * @修改手机号
     * created 在 2021/11/15 15:30 创建
     * @author SunWu
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function changeMobile(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
                'code' => 'required',//验证码
                'mobile' => 'required|regex:/^1[345789][0-9]{9}$/',
            ],
            [
                'code.required' => '参数`验证码`缺失',
                'mobile.required' => '手机号不能为空，请输入手机号',
                'mobile.regex' => '手机号格式错误，请重试',
            ]
        );

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        return response()->json(
            UsersService::changeMobile(
                $this->getUserId(),
                $this->getUserTpye(),
                $data
            )
        );
    }

    /**
     * @修改用户信息
     * created 在 2021/11/15 16:39 创建
     * @author SunWu
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function modifyUserinfo(Request $request)
    {
        $data = $request->all();
        return response()->json(UsersService::modifyUserinfo($this->getUserId(), $data));
    }

    /**
     * @修改用户密码
     * created 在 2021/11/16 09:23 创建
     * @author SunWu
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function changePassword(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
                'old_pwd' => 'required',//旧密码
                'new_pwd' => 'required',//新密码
                'confirm_pwd' => 'required',//确认密码
            ],
            [
                'old_pwd.required' => '请输入旧密码',
                'new_pwd.required' => '请输入新密码',
                'confirm_pwd.required' => '请输入确认密码',
            ]
        );

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        if($data['new_pwd'] != $data['confirm_pwd']) {
            return response()->json([
                'code' => 1,
                'msg' => '两次输入的密码不一致，请重新输入',
                'data' => '',
            ]);
        }

        return response()->json(UsersService::changePassword($this->getUserId(), $data));
    }

    /**
     * @个人中心
     * created 在 2021/11/23 16:53 创建
     * @author SunWu
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function userCenter(Request $request)
    {
        return $this->success(
            UsersService::userCenter($this->getUserId(), $this->getMainUserId())
        );
    }

    /**
     * 解除微信绑定
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @author ソンブ
     * @created_at: 2022/1/28 9:59
     */
    public function relieveWechatBind(Request $request){
        $adminInfo = AdminModel::where('id', $this->getUserId())->first();

        if(!empty($adminInfo['openid'])) {
            AdminModel::where('id', $this->getUserId())->update([
                'openid' => '',
                'wx_nickname' => ''
            ]);
        }

        return $this->success();
    }

    public function wechatBind(Request $request)
    {
        $adminInfo = AdminModel::where('id', $this->getUserId())->first();

        $wxinfo = json_decode(LoginService::getOpenId($request->code), true);

        if(empty($adminInfo['openid']) && !empty($request->code)) {
            AdminModel::where('id', $this->getUserId())->update([
                'openid' => $wxinfo['openid'],
                'wx_nickname' => $request->nickname
            ]);
        }

        return $this->success();
    }

    /**
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @author ソンブ
     * @created_at: 2022/2/17 10:44
     */
    public function inviteList(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
                'pageSize' =>'required|integer',//页面大小
                'currentPage' =>'required|integer',//当前页
            ],
            [
                'pageSize.required' => '参数`pageSize`缺失',
                'pageSize.integer' => '参数`pageSize`只能为数字',
                'currentPage.required' => '参数`currentPage`缺失',
                'currentPage.integer' => '参数`currentPage`只能为数字',
            ]
        );

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info, 1);
        }

        if($this->getUserTpye() == 1) {
            return $this->fail('', '您的权限不足，无法查看被邀请人信息');
        }

        return $this->success(
            UsersService::inviteList(
                $this->getMainUserId(),
                $data
            )
        );
    }
}
